from rest_framework import serializers
from django.db import transaction
from goods.models import SKU, GoodsCategory, SPU, SKUSpecification, SpecificationOption, SPUSpecification


# 前端传过来的sku规格数据  序列化器嵌套
class SKUSpecifcationSerializer(serializers.Serializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()


# sku增删改查
class SKUSeriallizer(serializers.ModelSerializer):
    category_id = serializers.IntegerField()
    category = serializers.CharField(read_only=True)
    spu_id = serializers.IntegerField()
    spu = serializers.CharField(read_only=True)
    # 重写规格字段
    specs = SKUSpecifcationSerializer(read_only=True, many=True)

    class Meta:
        model = SKU
        fields = '__all__'

    @transaction.atomic
    def create(self, validated_data):
        sid = transaction.savepoint()
        try:
            sku = SKU.objects.create(**validated_data)
            specs = self.context["request"].data["specs"]
            for spec in specs:
                SKUSpecification.objects.create(option_id=spec["option_id"], spec_id=spec["spec_id"], sku_id=sku.id)
        except Exception as e:
            transaction.savepoint_rollback(sid)
            raise serializers.ValidationError("数据入库失败")
        else:
            transaction.savepoint_commit(sid)
            return sku

    @transaction.atomic
    def update(self, instance, validated_data):
        sid = transaction.savepoint()
        try:
            sku = SKU.objects.filter(id=instance.id).update(**validated_data)
            specs = self.context["request"].data["specs"]
            [spec.delete() for spec in instance.specs.all()]
            for spec in specs:
                SKUSpecification.objects.create(option_id=spec["option_id"], spec_id=spec["spec_id"],
                                                sku_id=instance.id)
        except Exception as e:
            transaction.savepoint_rollback(sid)
            raise serializers.ValidationError("数据修改失败")
        else:
            transaction.savepoint_commit(sid)
            return instance


class SKUCategorySeriallizer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = ["id", "name"]


class GoodSimpleSeriallizer(serializers.ModelSerializer):
    class Meta:
        model = SPU
        fields = ["id", "name"]


class SpecOptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = SpecificationOption
        fields = ["id", "value"]


class GoodSpecsSeriallizer(serializers.ModelSerializer):
    # 规格关联的选项；规格一方， 选项是多方
    options = SpecOptionSerializer(read_only=True, many=True)

    class Meta:
        model = SPUSpecification
        fields = "__all__"
